const models = require('../db/mysqldb/index')
const sequelize = require('sequelize/index')
const Op = sequelize.Op
const { ErrorModel, SuccessModel, sonsTree } = require('../utils/index')
const logger = require('../utils/logger')
const _ = require('lodash')

class SysDeptController {
  /**
   * @description 根据用户的dept_id 获取部门
   * @param {*} user.dept_id
   */
  static async getDeptList(req, res, next) {
    const { user } = req
    logger.info(`SysDeptController`, `getDeptList`, `user`, user)
    try {
      const { dept_id } = user
      const child_dept_id = await models.sequelize.query(
        `SELECT t3.*  FROM (SELECT t1.dept_id, IF ( find_in_set( t1.parent_id, @pids ) > 0, @pids := concat( @pids, ',', t1.dept_id ), 0 ) AS ischild 
                        FROM ( SELECT dept_id, parent_id FROM sys_dept t WHERE t.del_flag = '0' ORDER BY parent_id, dept_id ) t1, ( SELECT @pids := ${dept_id} dept_id ) t2 
                          ) t3 WHERE t3.ischild != 0`,
        { type: sequelize.QueryTypes.SELECT }
      )
      logger.info(
        `SysDeptController`,
        `getDeptList`,
        `child_dept_id`,
        child_dept_id
      )
      // 本身dept_id 与 子孙dept_id
      let ids = [dept_id]
      child_dept_id.forEach(ele => {
        ids.push(ele.dept_id)
      })
      const res_dept = await models.sys_dept.findAll({
        where: {
          dept_id: {
            [Op.in]: ids
          }
        }
      })
      logger.info(`SysDeptController`, `getDeptList`, `res_dept`, res_dept)
      res.json(new SuccessModel(res_dept))
    } catch (error) {
      logger.error(`SysDeptController`, `getDeptList`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
   * @description 获取部门下所有节点 并以tree结构树返回
   * @param {*} user.dept_id
   */
  static async getDeptTree(req, res, next) {
    const { user } = req
    logger.info(`SysDeptController`, `getDeptTree`, `user`, user)
    try {
      const { dept_id } = user
      const child_dept_id = await models.sequelize.query(
        `SELECT t3.*  FROM (SELECT t1.dept_id, IF ( find_in_set( t1.parent_id, @pids ) > 0, @pids := concat( @pids, ',', t1.dept_id ), 0 ) AS ischild 
                        FROM ( SELECT dept_id, parent_id FROM sys_dept t WHERE t.del_flag = '0' ORDER BY parent_id, dept_id ) t1, ( SELECT @pids := ${dept_id} dept_id ) t2 
                          ) t3 WHERE t3.ischild != 0`,
        { type: sequelize.QueryTypes.SELECT }
      )
      logger.info(
        `SysDeptController`,
        `getDeptTree`,
        `child_dept_id`,
        child_dept_id
      )
      // 本身dept_id 与 子孙dept_id
      let ids = [dept_id]
      child_dept_id.forEach(ele => {
        ids.push(ele.dept_id)
      })
      const res_dept = await models.sys_dept.findAll({
        where: {
          dept_id: {
            [Op.in]: ids
          }
        }
      })
      logger.info(`SysDeptController`, `getDeptTree`, `res_dept`, res_dept)
      const tree_dept = sonsTree(res_dept, dept_id, 'dept_id')
      logger.info(`SysDeptController`, `getDeptTree`, `tree_dept`, tree_dept)
      res.json(new SuccessModel(tree_dept))
    } catch (error) {
      logger.error(`SysDeptController`, `getDeptTree`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
   * @description 新增部门
   * @param {*} dept_name
   * @param {*} sort
   * @param {*} parent_id
   */
  static async addDept(req, res, next) {
    const { dept_name, sort = 0, parent_id } = req.body
    logger.info(`SysDeptController`, `addDept`, `req.body`, req.body)
    try {
      // 判断部门名称 部门父级id是否存在
      if (!dept_name.trim() || !parent_id) {
        res.json(new ErrorModel('缺少必填项'))
        return
      }
      // 查找是否存在相同的部门名称
      const dept_find_info = await models.sys_dept.findOne({
        where: {
          dept_name: dept_name.trim()
        }
      })
      if (dept_find_info) {
        res.json(new ErrorModel('此部门已存在'))
        return
      }
      // 添加部门
      const dept_add_info = await models.sys_dept.create({
        dept_name,
        sort,
        parent_id
      })
      logger.info(
        `SysDeptController`,
        `addDept`,
        `dept_add_info`,
        dept_add_info
      )
      if (!dept_add_info.dept_id) {
        res.json(new ErrorModel([], '新增失败'))
        return
      }
      res.json(new SuccessModel([], '新增成功'))
    } catch (error) {
      logger.error(`SysDeptController`, `addDept`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
   * @description 编辑部门
   * @param {*} dept_id
   * @param {*} dept_name
   * @param {*} sort
   * @param {*} parent_id
   */
  static async editDept(req, res, next) {
    const { dept_id, dept_name, sort = 0, parent_id } = req.body
    logger.info(`SysDeptController`, `editDept`, `req.body`, req.body)
    try {
      // 判断部门名称 部门父级id是否存在
      console.log(parent_id.trim())
      if (!dept_id || !dept_name.trim() || !parent_id) {
        res.json(new ErrorModel('缺少必填项'))
        return
      }
      // 查找是否存在相同的部门名称 除去本身
      const dept_find_info = await models.sys_dept.findOne({
        where: {
          dept_name: dept_name.trim(),
          dept_id: {
            [Op.ne]: dept_id
          }
        }
      })
      if (dept_find_info) {
        res.json(new ErrorModel('此部门已存在'))
        return
      }
      // 更新部门
      const dept_edit_info = await models.sys_dept.update(
        {
          dept_name,
          sort,
          parent_id,
          update_date_timestamp: Date.now()
        },
        {
          where: {
            dept_id
          }
        }
      )
      logger.info(
        `SysDeptController`,
        `editDept`,
        `dept_edit_info`,
        dept_edit_info
      )
      res.json(new SuccessModel([], '更新成功'))
    } catch (error) {
      logger.error(`SysDeptController`, `editDept`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
   * @description 删除部门
   * @param {*} dept_id
   * @param {*} dept_name
   * @param {*} sort
   * @param {*} parent_id
   */
  static async delDept(req, res, next) {
    const { dept_id } = req.body
    logger.info(`SysDeptController`, `delDept`, `req.body`, req.body)
    try {
      // 判断部门名称 部门父级id是否存在
      if (!dept_id) {
        res.json(new ErrorModel('缺少必填项'))
        return
      }
      // 删除部门
      const dept_del_info = await models.sys_dept.update(
        { del_flag: '1' },
        {
          where: {
            dept_id
          }
        }
      )
      logger.info(
        `SysDeptController`,
        `delDept`,
        `dept_del_info`,
        dept_del_info
      )
      res.json(new SuccessModel([], '删除成功'))
    } catch (error) {
      logger.error(`SysDeptController`, `delDept`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
}
module.exports = {
  SysDeptController
}
